package com.sunxueqi.project.blog.service.impl;

import java.sql.Timestamp;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import com.sunxueqi.common.constant.StatusConstants;
import com.sunxueqi.common.util.KeyGenerate;
import com.sunxueqi.common.util.SecurityUtils;
import com.sunxueqi.project.blog.dao.BlogMapper;
import com.sunxueqi.project.blog.service.IBlogService;
import com.sunxueqi.project.blog.vo.Blog;

import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.IdUtil;

@Service
public class BlogServiceImpl implements IBlogService {

	@Value("${blogPath}")
	private String blogPath;
	
	@Autowired
	private BlogMapper blogMapper;
	
	@Override
	public List<Blog> selectBlogList(@RequestBody Blog blog) {
		List<Blog> blogList = blogMapper.selectBlogList(blog);
		return blogList;
	}

	@Override
	public Blog selectBlogById(String id) {
		Blog blog = blogMapper.selectByPrimaryKey(id);
		return blog;
	}
	
	@Override
	public int insertBlog(Blog blog) {
		
		
		String id = KeyGenerate.getKeyId();
		
		String fileName = blog.getTitle()+ id;
		FileWriter fileWriter = new FileWriter(blogPath + fileName + ".txt");
		fileWriter.write(blog.getContent());
		
		blog.setId(id);
		blog.setDeleteStatus(StatusConstants.NORMAL);
		blog.setContent(fileName);
		blog.setClick(StatusConstants.INIT_NUM);
		blog.setIsLike(StatusConstants.INIT_NUM);
		blog.setCreateTime(new Timestamp(System.currentTimeMillis()));
		//blog.setCreateBy(SecurityUtils.getUserId());
		
		int count = blogMapper.insert(blog);
		return count;
	}

	@Override
	public int updateBlog(Blog blog) {
		// blog.setUpdateBy(SecurityUtils.getUserId());
		blog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		int count = blogMapper.updateByPrimaryKeySelective(blog);
		return count;
	}

	@Override
	public int deleteBlogById(String[] idArray) {
		
		int result = 0;
		for (String id : idArray) {
			Blog blog = new Blog();
			blog.setId(id);
			blog.setDeleteStatus(StatusConstants.DELETED);
			//blog.setDeleteBy(SecurityUtils.getUserId());
			blog.setDeleteTime(new Timestamp(System.currentTimeMillis()));
			int count = blogMapper.updateByPrimaryKeySelective(blog);
			result += count;
		}
		return result;
	}


}
